<template>
    <!-- 滚动区域开始 -->
    <view class="container">
        <z-paging
            ref="paging"
            :scroll-with-animation="true"
        >
            <template #top>
                <!-- 自定义导航区域开始 -->
                <TridentNavBar>
                    <template #left>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i class="iconfont icon-zuojiantou" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                    <template #default>发起群聊</template>
                    <template #right>
                        <!-- #ifdef MP-ALIPAY -->
                        <i class="iconfont icon-home" @click="goto('/pages/index/index')" style="font-size: 36rpx;font-weight: bold;"></i>
                        <!-- #else -->
                        <i class="iconfont icon-home" @click="goto('/pages/index/index')" style="font-size: 36rpx;"></i>
                        <!-- #endif -->
                    </template>
                </TridentNavBar>
                <!-- 自定义导航区域结束 -->

                <!-- 搜索区域开始 -->
                <TridentSearch @search="handleSearch"/>
                <!-- 搜索区域结束 -->
            </template>

            <uv-index-list
                :index-list="Object.keys(generalFriendList)"
                :activeColor="global.THEME_COLOR"
                customNavHeight="120rpx"
            >
                <template v-slot:header>
                    <view>
                        <TridentCellItem :item="{title: '选择一个群'}" @click="goto('/pagesGroup/index/index')"/>
                        <TridentCellItem :item="{title: '面对面建群'}"/>

                        <!-- 星标好友区域开始 -->
                        <view class="star-wrap">
                            <view class="title-box">星标朋友</view>
                            <!-- 骨架屏 -->
                            <uv-skeletons :loading="isSkeleton" :skeleton="skeletons"></uv-skeletons>
                            <view class="friend-box">
                                <TridentFriendItem v-for="(item, index) in starFriendList" :friend="item" :key="index" :isShowCheck="true" @click="handleChange(item)"/>
                            </view>
                        </view>
                        <!-- 星标好友区域结束 -->
                    </view>
                </template>

                <!-- 普通好友区域开始 -->
                <template v-for="(item, index) in generalFriendList" :key="index">
                    <uv-index-item>
                        <uv-index-anchor
                            :text="index"
                            bgColor="#e2f8f3"
                            customNavHeight="50"
                        />
                        <view class="general-wrap">
                            <TridentFriendItem v-for="(friend, index) in item" :friend="friend" :key="index" :isShowCheck="true" @click="handleChange(friend)"/>
                        </view>
                    </uv-index-item>
                </template>
            </uv-index-list>

            <!-- 底部操作区域开始 -->
            <div class="footer-wrap">
                <div class="btn-box" :class="{actived: createGroupChatParams.member.length > 0}" @click="handleShowCreateGroupChat">完成</div>
            </div>

            <!-- 创建群聊名称弹层开始 -->
            <uni-popup
                ref="popupGroupRef"
                type="bottom"
                background-color="#fff"
                :mask-click="false"
            >
                <view class="popup-wrap">
                    <view class="title-box">
                        <text>创建群聊</text>
                        <i class="iconfont icon-guanbi" @click="handleClosePopup"></i>
                    </view>
                    <view class="input-box">
                        <uni-forms
                            ref="formRef"
                            :rules="rules"
                            :modelValue="createGroupChatParams"
                        >
                            <!-- 群聊名称 -->
                            <uni-forms-item label="名称" required name="name">
                                <uni-easyinput type="text" :primaryColor="global.THEME_COLOR" v-model="createGroupChatParams.name" placeholder="请输入名称" />
                            </uni-forms-item>

                            <!-- 备注 -->
                            <uni-forms-item label="备注">
                                <uni-easyinput type="text" :primaryColor="global.THEME_COLOR" v-model="createGroupChatParams.note" placeholder="请输入备注" />
                            </uni-forms-item>
                        </uni-forms>
                    </view>

                    <TridentButton @handleClick="handleCreateGroupChat"/>
                </view>
            </uni-popup>
            <!-- 创建群聊名称弹层结束 -->
        </z-paging>
    </view>
</template>

<script lang="ts" setup>
import { goto } from '@/utils/tools'
import { reqFriendListAPI } from '@/apis/friend'
import { reqCreateGroupChatAPI } from '@/apis/groupChat'
import { useUserStore } from '@/stores'
import type { Friend, FriendListParams } from '@/types/friend'
import type { CreateGroupChatParams } from '@/types/groupChat'
import { pinyin } from 'pinyin-pro'
import { inject, reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'



// --------------- 定义全局变量开始 ---------------
// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()
// --------------- 定义全局变量结束 ---------------



onShow(async() => {
    for (let index = 0; index < 10; index++) {
        skeletons.push(skeleton as never)
    }

    await getFriendList()
})



// -------------- 处理复选框变化开始 --------------
const handleChange = (friend: Friend) => {
    friend.is_check = !friend.is_check
    
    if (friend.is_check) {
        createGroupChatParams.value.member.push({
            uid: friend.info.uid,
            username: friend.info.username,
            avatar_url: friend.info.avatar_url,
            mobile: friend.info.mobile,
            is_disturb: 0,
            is_top: 0,
            is_check: false
        })
    } else {
        const index = createGroupChatParams.value.member.findIndex(item => item.uid == friend.info.uid)
        createGroupChatParams.value.member.splice(index, 1)
    }
}
// -------------- 处理复选框变化结束 --------------



// --------------- 处理创建群聊开始 ---------------
const popupGroupRef = ref()

// 创建群聊参数
const createGroupChatParams = ref<CreateGroupChatParams>({
    name: '',
    member: [],
    note: '',
    network: 'ws',
})

const formRef = ref()

// 验证规则
const rules = {
    name: {
		rules: [{
			required: true,
			errorMessage: '名称不能为空'
		}]
	},
}

// 显示群聊弹层
const handleShowCreateGroupChat = () => {
    if (createGroupChatParams.value.member.length < 2) {
        uni.showToast({
            title: '群聊至少勾选2个好友',
            duration: 1000,
            icon: 'none'
        })
        return false
    }
        
    popupGroupRef.value.open('bottom')
}

// 创建群聊
const handleCreateGroupChat = () => {
    formRef.value.validate().then(async () => {
        const result = await reqCreateGroupChatAPI(createGroupChatParams.value)
        uni.showToast({
            title: '创建群聊成功',
            duration: 1000
        })

        setTimeout(() => {
            popupGroupRef.value.close()
            uni.navigateTo({url: '/pages/chat/index?mode=2&gid=' + result.data.id})
        }, 1000)
    }).catch(() => {
	})
}

// 处理关闭别名弹层
const handleClosePopup = () => {
    popupGroupRef.value.close()
}
// --------------- 处理创建群聊结束 ---------------



// --------------- 处理好友列表开始 ---------------
const params = ref<FriendListParams>({
    username: '',
    is_my_friend: 1,
    is_friend_info: 1,
    status: '1',
    page: 1,
    page_size: -1
})

// 全部好友列表
const allFriendList = ref<Friend[]>([])

// 星标好友列表
const starFriendList = ref<Friend[]>([])

// 普通好友列表
const generalFriendList: any = ref({})

// 获取好友列表
const getFriendList = async () => {
    isSkeleton.value = true
    const result = await reqFriendListAPI(params.value)
    starFriendList.value = []
    allFriendList.value = result.data.friends
    let tempFriendList: any = {}
    result.data.friends.forEach(item => {
        item.is_check = false
        let is_asterisk = ''
        item.information.forEach(value => {
            if (value.uid != userStore.profile.user?.uid) {
                is_asterisk = value.is_asterisk
            }
        })

        if (is_asterisk == '1') {
            starFriendList.value.push(item)
        } else  {
            let initial = pinyin(item.info.username, {pattern: 'first', toneType: 'none' }).substr(0, 1).toLocaleUpperCase()
            
            if (!tempFriendList[initial]) {
                tempFriendList[initial] = []
            }

            tempFriendList[initial].push(item)
        }
    })

    generalFriendList.value = Object.keys(tempFriendList).sort().reduce((acc: any, key) => {
        acc[key] = tempFriendList[key];
        return acc;
    }, {});

    isSkeleton.value = false
}
// --------------- 处理好友列表结束 ---------------



// --------------- 搜索好友功能开始 ---------------
// 处理搜索
const handleSearch = async (e: any) => {
    params.value.username = e.keyword.value
    await getFriendList()
}
// --------------- 搜索好友功能结束 ---------------



// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive({
  type: 'flex',
  num: 1,
  style: 'padding: 15rpx 30rpx 15rpx 25rpx;background-color: #fff;border-bottom: 2rpx solid #f6f6f6;align-items: center;',
  children: [
    // 选择框区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 42rpx;height: 42rpx;border-radius: 21rpx;margin-right: 20rpx;'
    },

    // 图片区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 90rpx;height: 90rpx;border-radius: 10rpx;margin-right: 20rpx;'
    },

    {
      type: 'custom',
      num: 1,
      style: ['width: 180rpx;height: 40rpx;']
    }
  ]
})

const skeletons = reactive([])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
.container {
    padding-bottom: 90rpx;
    // 星标好友区域开始
    .star-wrap {
        .title-box {
            padding-left: 30rpx;
            background-color: #e1e1e2;
            height: 70rpx;
            line-height: 70rpx;
        }

        .friend-box {
            padding-left: 30rpx;
            background-color: #fff;
        }
    }
    // 星标好友区域结束

    // 普通好友区域开始
    .general-wrap {
        background-color: #fff;
        padding: 0 30rpx;
    }
    // 普通好友区域结束

    // 底部操作区域开始
    .footer-wrap {
        display: flex;
        position: fixed;
        bottom: 0;
        left: 0;
        height: 90rpx;
        background-color: #F7F7F7;
        width: 100%;
        justify-content: flex-end;
        align-items: center;
        border-top: 2rpx solid #bcbaba;
        z-index: 100;
        .btn-box {
            height: 60rpx;
            line-height: 60rpx;
            border: 2rpx solid #c6c5c5;
            margin-right: 80rpx;
            width: 120rpx;
            text-align: center;
            border-radius: 8rpx;
            color: #bcbaba;
            &.actived {
                color: $uni-color-primary;
                border: 2rpx solid $uni-color-primary;
            }
        }
    }

    // 创建群聊弹层区域开始
    .popup-wrap {
        .title-box {
            display: flex;
            align-items: center;
            font-size: 32rpx;
            font-weight: bold;
            justify-content: center;
            height: 80rpx;
            color: $uni-color-primary;
            position: relative;
            border-bottom: 2rpx solid #e3e2e2;
            .icon-guanbi {
                font-size: 44rpx;
                color: #8e8c8c;
                position: absolute;
                right: 20rpx;
            }
        }

        // 输入框区域
        .input-box {
            padding: 30rpx 20rpx 0 20rpx;
        }
    }
}
</style>